//
//  BHImagePreviewCollectionViewCell.swift
//  BigHealth
//
//  Created by 蔺百好 on 2021/7/7.
//

import UIKit

class BHImagePreviewCollectionViewCell: UICollectionViewCell {
    
    var dissMissTapActBlock:(() -> Void)?
    
    
    lazy var imageScrollView: UIScrollView = {
        let view = UIScrollView.init()
        view.maximumZoomScale = 2.5
        view.minimumZoomScale = 0.75
        view.delegate = self
        return view
    }()
    lazy var image_view: UIImageView = {
        let view = UIImageView.init()
        view.contentMode = .scaleAspectFit
        return view
    }()
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        self.imageScrollView.frame = CGRect(x: 5, y: 0, width: self.bh_width-10, height: self.bounds.height)
        self.image_view.frame = CGRect(x: 5, y: 0, width: self.bh_width-10, height: self.bounds.height)

        self.contentView.addSubview(self.imageScrollView)
        self.imageScrollView.addSubview(self.image_view)
        self.imageScrollView.zoomScale = 1.0
        
        self.image_view.addViewAction {[weak self] (_) in
            self?.dissMissTapActBlock?()
        }

    }
    

    var model: BHImageOrVideoModel! {
        didSet {
            self.imageScrollView.zoomScale = 1.0
            if model.imageUrl == nil {
               
                model.transAssetToImage {[weak self] (img) in
                    if img == nil {
                        return
                    }
                    self?.image_view.image = img
                }
            }else {
                self.image_view.sd_setImage(with: URL.init(string: model.imageUrl ?? ""), completed: nil)
            }
        }
    }
    
}
extension BHImagePreviewCollectionViewCell: UIScrollViewDelegate {
    //可缩放的view
       func viewForZooming(in scrollView: UIScrollView) -> UIView? {
           return self.image_view
       }
       
       //缩放响应，设置imageView的中心位置
       func scrollViewDidZoom(_ scrollView: UIScrollView) {
           var centerX = scrollView.center.x
           var centerY = scrollView.center.y
           centerX = scrollView.contentSize.width > scrollView.frame.size.width ?
               scrollView.contentSize.width/2:centerX
           centerY = scrollView.contentSize.height > scrollView.frame.size.height ?
               scrollView.contentSize.height/2:centerY
           self.image_view.center = CGPoint(x: centerX, y: centerY)
       }
}
